package com.demo.controller;

import com.demo.pojo.Teacher;
import com.demo.pojo.bo.TeacherBO;
import com.demo.service.TeacherService;
import com.demo.utils.JSONResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @RequestMapping("get")
    public JSONResult getTeacher(@RequestParam String id) {
        Teacher teacher = teacherService.queryById(id);
        return JSONResult.ok(teacher);
    }

    @RequestMapping("get2")
    public JSONResult getTeacher2(@RequestParam String sex, @RequestParam Integer age) {
        List<Teacher> list = teacherService.queryByCondition(sex, age);
        return JSONResult.ok(list);
    }

    @RequestMapping("delete")
    public JSONResult deleteTeacher() {
        Teacher teacher = new Teacher();
        teacher.setId("371d9339-8f11-4ec0-a590-e181f21a92b8");
        teacherService.deleteTeacher(teacher);
        return JSONResult.ok(teacher);
    }

    @RequestMapping("update")
    public JSONResult updateTeacher() {
        Teacher teacher = new Teacher();
        teacher.setId("371d9339-8f11-4ec0-a590-e181f21a92b8");
        teacher.setName("tester");
        teacher.setAge(123);
        teacher.setSex("female");
        teacherService.updateTeacher(teacher);
        return JSONResult.ok("success");
    }

    @PostMapping("create")
    public JSONResult createTeacher(@Valid @RequestBody TeacherBO teacherBO, BindingResult result) {
        // @Valid 对 teacherBO 进行校验, 返回 result
        // @RequestBody 主要用来接收前端传递给后端的 json 字符串中的数据的(请求体中的数据的)

        // 判断 result 是否有错误
        if (result.hasErrors()) {
            Map<String, String> map = getErrors(result);
            return JSONResult.errorMap(map);
        }

        String sid = UUID.randomUUID().toString();
        Teacher teacher = new Teacher();

        // 将 teacherBO 对象中的属性, 拷贝到 teacher 对象里
        BeanUtils.copyProperties(teacherBO, teacher);
        teacher.setId(sid);

        teacherService.saveTeacher(teacher);
        return JSONResult.ok();
    }

    private Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            String field = error.getField();
            String msg = error.getDefaultMessage();
            map.put(field, msg);
        }

        return map;
    }
}
